package XMLCreator;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collection;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import Main.Pair;

public class XMLSpliter2{

	private static String getValue(String field,Element fstElmnt){
		try {
			NodeList lstNmElmntLst = fstElmnt.getElementsByTagName(field);
			Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
			if (lstNmElmnt == null)
				return null;
			NodeList lstNm = lstNmElmnt.getChildNodes();
			return ((Node) lstNm.item(0)).getNodeValue();
		} catch (Exception e) {
			System.out.println("XMLSpliter2.getValue catch Exception field="+field);//TODO
			return "";
		}		
	}

	//	private String addZeros(int lenOfNum){
	//		
	//	}

	private static void makeFiles(String nameDirOut,String nameDirHtml,String index,String text){
		FileWriter writer;
		try {
//			writer = new FileWriter(new File(nameDirHtml+index+".html"));
//			writer.write(text);
//			writer.close();
//			writer = new FileWriter(new File(nameDirOut+index+".txt"));
//			writer.write(SecondParse.htmlToText(text));
//			writer.close();
			writer = new FileWriter(new File(nameDirOut+index+".txt"));
			writer.write(text);
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	//	private static void makeFile(String nameDirOut,int index,String title,String id,String text,String author,String date){
	//		FileWriter writer;
	//		try {
	//			writer = new FileWriter(new File(nameDirOut+index));
	//			//writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<all>\n<me>");
	//			writer.write(text);
	//			writer.close();
	//		} catch (IOException e) {
	//			// TODO Auto-generated catch block
	//			e.printStackTrace();
	//		}
	//		
	//	}

	private static String addZeros(int maxLen, String idStr){
		while(idStr.length()<maxLen){
			idStr="0"+idStr;

		}
		return idStr;
	}

	// in the metadata is pair <a,b> a- the name that we call him (in the corpus) b- the name that he had in the xml
	public static void makeSplit(String nameFileIn,String nameDirOutText,String nameDirOutMetadata,String nameDirOutHtml,Collection<Pair<String, String>> metadata,FileWriter articlesWriter){
		int maxLen = maxLen(nameFileIn);
		if (maxLen==-1){
			System.out.println("Error 6 in XMLSpliter2");//TODO XMLSpliter2
		}
		try {
			File file = new File(nameFileIn);
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(file);
			doc.getDocumentElement().normalize();
			NodeList nodeLst = doc.getElementsByTagName("page");

			for (int s = 0; s < nodeLst.getLength(); s++) {
				Node fstNode = nodeLst.item(s);

				if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
					Element fstElmnt = (Element) fstNode;
					//String title=getValue("title", fstElmnt);//TODO do whis it samthing
					//String id=index+"";
					String id=getValue("id", fstElmnt);
					id=addZeros(maxLen, id);
					//String time=getValue("timestamp", fstElmnt);
					//String username=getValue("username", fstElmnt);

					String text2=getValue("text", fstElmnt);

					if (text2.equals("")){//TODO
						continue;
					}
					
					Pair<String, Collection<String>> afterParse=new WikiParser().parse(text2);


					String text=afterParse.getFirst().trim();
					if (!text.startsWith("#")){	
						if (catFilter(afterParse.getSecend())){

							FileWriter writer = new FileWriter(new File(nameDirOutMetadata+id+".txt"));

							for(Pair<String, String> oneMatadata : metadata){
								String value=getValue(oneMatadata.getSecend(), fstElmnt);							
								writer.write(oneMatadata.getFirst()+" == "+value+"\n");
							}					
							writer.write("cat == "+afterParse.getSecend()+"\n");
							writer.close();
							makeFiles(nameDirOutText,nameDirOutHtml,id,text);
							articlesWriter.write(id+".txt\n");
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
			System.out.println("Error 1 in XMLSpliter2");//TODO XMLSpliter2
		}		
	}

	private static boolean catFilter(Collection<String> secend) {
		for(String cat : secend){
			cat=cat.toLowerCase();
			if (cat.contains("greeks") || cat.contains("greek") || cat.contains("greece") ||
					cat.contains("rome") || cat.contains("roman"))
				return true;
		}
		return false;
	}

	public static int maxLen(String nameFileIn){
		try {
			int maxLen=0;
			File file = new File(nameFileIn);
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(file);
			doc.getDocumentElement().normalize();
			NodeList nodeLst = doc.getElementsByTagName("page");

			for (int s = 0; s < nodeLst.getLength(); s++) {
				Node fstNode = nodeLst.item(s);

				if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
					Element fstElmnt = (Element) fstNode;
					String id=getValue("id", fstElmnt);
					if (id.length()>maxLen)
						maxLen=id.length();
				}
			}
			return maxLen;
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
			System.out.println("Error 2 in XMLSpliter2 ");//TODO XMLSpliter2
		}
		System.out.println("Error 3 XMLSpliter2");//TODO XMLSpliter2
		return -1;
	}
}	

